var app = getApp();
var a = require("../../utils/public");
var status = require('../../utils/index.js');
var util = require('../../utils/util.js');
var wcache = require('../../utils/wcache.js');

Page({
    data: {
        placeholdeImg: app.globalData.placeholdeImg,
        navList: [{
            name: "出售中",
            status: "1"
        }, {
            name: "库存预警",
            status: "8"
        }, {
            name: "已下架",
            status: "0"
        }, {
            name: "待审核",
            status: "4"
        }
        ],
        currentTab: 1,
        list: [],
        loadText: "加载中...",
        noData: 0,
        loadMore: true,
        showActionsheet: false,
        groups: [
            { text: '删除', type: 'warn', value: 1 },
            { text: '编辑', value: 2 },
            { text: '修改库存', value: 5 }
            // { text: '编辑', value: 3 }
        ],
        buttons: [{ text: '取消' }, { text: '确定' }],
        editSkuNum: 0,
        rushCategoryData: {
            tabs: [],
            activeIndex: 0
        },
        categoryScrollBarTop: 0,
        resetScrollBarTop: 0,
        scrollViewHeight: 0,
        isFirstCategory: true,
        isLastCategory: false,
        pageEmpty: false,
        active_sub_index: 0,
        keywords: '',
    },
    $data: {
        options: {},
        rushCategoryId: "",
        pageNum: 1,
        actIds: [],
        loading: true,
        isScrollTop: true,
        isScrollBottom: false,
        scrollInfo: null,
        isSetCategoryScrollBarTop: true,
        touchStartPos: {
            pageX: 0,
            pageY: 0
        },
        list: []
    },
    page: 1,
    keywords: '',
    goodsId: '', //当前操作的商品id

    onLoad: function (options) {
        let that = this;
        this.getScrollViewHeight();
        this.setData({
            subCateHeight: this.getPx(44)
        })
        let currentTab = options.status || 1;
        this.setData({
            currentTab,
            list:[]
        }, () => {
            // this.getHotList();
        })
        this.$data.rushCategoryId = app.globalData.typeCateId || 0;
        app.globalData.typeCateId = 0;
    },
    /**
     * 初始化数据
     */
    initPageData: function () {
        var t = this;
        this.setData({
            isFirstCategory: true,
            isLastCategory: false,
            list: [],
            resetScrollBarTop: 0
        }, function () {
            t.getHotList();
        });
    },
    /**
   * 搜索栏高度
   */
    getScrollViewHeight: function () {
        var that = this,navHeight;
        wx.createSelectorQuery().select(".nav").boundingClientRect(function (res) {
            navHeight = res.height;
            console.log(res);
            wx.createSelectorQuery().select(".search-bar").boundingClientRect(function (res1) {
                console.log(res1);
                res.height && that.setData({
                    scrollViewHeight: wx.getSystemInfoSync().windowHeight - res1.height  - res.height
                });
            }).exec();
        }).exec();
    },
    
    goLink:function(){
        wx.navigateTo({
            url: '/lionfish_comshop/moduleB/supply/goodsadd'
        })
    },
    getPx: function (t) {
        return Math.round(app.globalData.systemInfo.windowWidth / 375 * t);
    },
    scrollBottom: function () {
        var t = this,
            e = this.$data,
            loading = e.loading;
        if (!loading) {
            e.loading = true;
            // this.getHotList();
            console.log(2222);
        }
    },

    touchstart: function (t) {
        if (t.changedTouches && t.changedTouches[0]) {
            var a = t.changedTouches[0],
                e = a.pageX,
                o = a.pageY;
            this.$data.touchStartPos = {
                pageX: e,
                pageY: o
            };
        }
    },

    touchend: function (t) {
        var a = this;
        if (t.changedTouches && t.changedTouches[0]) {
            var e = t.changedTouches[0],
                o = e.pageX,
                i = e.pageY,
                r = this.$data.touchStartPos,
                s = r.pageX,
                n = r.pageY,
                l = this.$data,
                g = l.isScrollTop,
                u = l.isScrollBottom,
                d = l.scrollInfo,
                c = (this.data.rushCategoryData, o - s),
                h = i - n;
            if (Math.abs(h) > Math.abs(c)) {
                if (h > 0) {
                    if (!g) return;
                    if (this.setData({
                        resetScrollBarTop: 0
                    }), h > 50) {
                        var m = this.data.rushCategoryData.activeIndex - 1;
                        if (m < 0) return;
                        this.setData({
                            resetScrollBarTop: 0
                        }, function () {
                            a.setCategory(m);
                        });
                    }
                } else {
                    if (!u || !this.data.canNext) return;
                    if (h < -50) {
                        var y = this.data.rushCategoryData,
                            p = y.activeIndex + 1;
                        if (p >= y.tabs.length || !this.$data.scrollInfo) return;
                        this.setData({
                            resetScrollBarTop: 0
                        }, function () {
                            a.setCategory(p);
                        });
                    }
                }
            } else {
                d && d.scrollTop < 50 && this.setData({
                    resetScrollBarTop: 0
                });
            }
        }
    },
    scroll: function (t) {
        var a = t.detail,
            e = a.scrollTop,
            o = a.scrollHeight,
            i = this.data,
            r = i.scrollViewHeight,
            s = i.loadMore;
        this.$data.scrollInfo = a, this.$data.isScrollTop = e <= 49, this.$data.isScrollBottom = !s && o - e - r <= 10;
    },
    get_cate_list: function () {
        let that = this;
        return new Promise((resolve, reject) => {
            app.util.request({
                'url': 'entry/wxapp/index',
                'data': {
                    controller: 'goods.get_category_list',
                    is_type_show: 1
                },
                dataType: 'json',
                success: function (res) {
                    if (res.data.code == 0) {
                        let leftList = res.data.data || [];
                        if (leftList.length == 0) {
                            wx.hideLoading();
                            that.setData({ noCateList: true })
                            return;
                        }

                        //判断分类是否变化
                        let cateNochange = false;
                        let oldRushCategoryData = that.data.rushCategoryData;
                        if (oldRushCategoryData && oldRushCategoryData.tabs && JSON.stringify(oldRushCategoryData.tabs) == JSON.stringify(leftList)) {
                            cateNochange = true;
                        }

                        let rushCategoryId = that.$data.rushCategoryId || leftList && leftList[0] && leftList[0].id || 0;
                        let active_index = 0;
                        if (that.$data.rushCategoryId) {
                            active_index = leftList.findIndex((p) => {
                                return p.id == that.$data.rushCategoryId
                            });
                        }
                        that.$data.rushCategoryId = rushCategoryId;
                        let rushCategoryData = {
                            tabs: leftList,
                            activeIndex: active_index
                        }
                        let isFirstCategory = !rushCategoryData.activeIndex;
                        let isLastCategory = rushCategoryData.activeIndex == rushCategoryData.tabs.length - 1;

                        console.log('cateNochange', cateNochange);
                        console.log('isFirst', that.isFirst);
                        if (!cateNochange) {
                            let h = {};
                            if (that.isFirst > 1) {
                                that.$data.pageNum = 1;
                                rushCategoryData = {
                                    tabs: leftList,
                                    activeIndex: 0
                                }
                                isFirstCategory = true;
                                isLastCategory = false;
                                that.$data.rushCategoryId = leftList[0] && leftList[0].id || 0;
                                h = {
                                    list: [],
                                    categoryScrollBarTop: 0,
                                    resetScrollBarTop: 50,
                                    loadMore: true,
                                    loadText: "加载中...",
                                    pageEmpty: false,
                                    active_sub_index: 0
                                };
                            }
                            that.setData({
                                ...h,
                                rushCategoryData,
                                isFirstCategory,
                                isLastCategory,
                                noCateList: false
                            }, () => {
                                that.initPageData();
                                wx.hideLoading();
                            })
                        }
                    } else {
                        // 分类不存在 todo
                    }
                    resolve();
                },
                fail: function (res) {
                    reject(res)
                }
            })
        })
    },
    // 切换子栏目
    change_sub_cate: function (e) {
        let rushCategoryData = this.data.rushCategoryData;
        let tabs = rushCategoryData.tabs;
        let active_index = rushCategoryData.activeIndex; //当前大栏目选中索引
        let active_sub_index = e.currentTarget.dataset.idx; //当前子栏目选中索引
        let active_cate_id = tabs[active_index].id; //当前大栏目选中id
        let active_subcate_id = e.currentTarget.dataset.id || active_cate_id;
        let scrollLeft = this.getPx(64) * active_sub_index;
        console.log(scrollLeft);
        let that = this;
        that.$data.pageNum = 1;
        that.$data.rushCategoryId = active_subcate_id;
        that.setData({
            showDrop: false,
            active_cate_id: active_subcate_id,
            active_sub_index: active_sub_index,
            list: [],
            scrollLeft: scrollLeft,
            showEmpty: false,
            loadMore: true,
            loadText: '加载中',
        }, () => {
            that.getHotList();
        })
    },
    showDrop: function () {
        this.setData({
            showDrop: !this.data.showDrop
        })
    },
    initFn: function (keywords = '') {
        this.page = 1;
        this.keywords = keywords;
        this.setData({
            list: [],
            loadText: "加载中...",
            noData: 0,
            loadMore: true,
        }, () => {
            this.getData();
        })
    },
    onHide: function () {
        this.setData({
            tabbarRefresh: false,
            changeCarCount: false
        })
    },
    reqPromise: function () {
        let that = this;

        return new Promise(function (resolve, reject) {
            let token = wx.getStorageSync('token');
            let cur_community = wx.getStorageSync('community');
            let rushCategoryId = that.$data.rushCategoryId;
            let grounding = that.data.currentTab;
            let keywords = that.data.keywords;
            console.log(111);
            app.util.request({
                url: 'entry/wxapp/index',
                data: {
                    controller: 'supplymobile.get_supply_goodslist',
                    token,
                    grounding,
                    page: that.$data.pageNum,
                    gid: rushCategoryId,
                    keywords
                },
                dataType: 'json',
                success: function (res) {
                    if (res.data.code == 0) {
                        let h = {};
                        let list = res.data.data;
                        if (list.length == 0) {
                            if (that.page == 1) {
                                
                                h.noData = 1;
                            } else {
                                h.loadMore = false;
                                h.noMore = false;
                                h.loadText = "没有更多记录了~"
                            }
                        }
                        
                        let rushList = that.data.list.concat(list);

                        // if (list.length < 10) h.noMore = true;
                        if (list.length < 30) { h.loadMore = false; h.canNext = true; }
                        h = {
                            ...h,
                            list: rushList,
                            pageEmpty: false
                        };
                        if (that.$data.pageNum == 1) h.resetScrollBarTop = 0;
                        // let oldList = that.data.list;
                        // list = oldList.concat(list);
                        
                        that.page++;
                        
                        h.loadText = that.data.loadMore ? "加载中..." : "没有更多商品了~";
                        that.$data.isSetCategoryScrollBarTop && (h.categoryScrollBarTop = 50  - (that.data.scrollViewHeight - 50) / 2);
                        that.setData(h, function () {
                            that.$data.loading = false, that.$data.pageNum += 1, !rushCategoryId;
                        })
                        console.log(that.data.list);
                    } else{
                        app.util.message(res.data.msg, 'switchTo:/lionfish_comshop/pages/user/me', 'error');
                    }
                    // resolve(res);
                }
            })
        });
    },
    getHotList: function () {
        var t = this,
            e = this.$data,
            rushCategoryId = e.rushCategoryId;
        this.$data.loading = true;

        this.reqPromise().then(function () {
            wx.stopPullDownRefresh();
        }).catch(function () {
            var a = {};
            rushCategoryId || (a.pageEmpty = true), t.$data.loading = false, t.setData(a), wx.stopPullDownRefresh();
        });
    },
    setCategory: function (t) {
        var that = this,
            rushCategoryData = this.data.rushCategoryData,
            tabs = rushCategoryData.tabs[t] || {},
            scrollViewHeight = this.data.scrollViewHeight;

        this.$data.rushCategoryId = tabs.id || null, this.$data.pageNum = 1, this.$data.isSetCategoryScrollBarTop = false;
        let isFirstCategory = !t;
        let isLastCategory = (t == rushCategoryData.tabs.length - 1);
        this.setData({
            "rushCategoryData.activeIndex": t,
            resetScrollBarTop: 0,
            categoryScrollBarTop: 50 * t - (scrollViewHeight - 50) / 2,
            list: [],
            canNext: false,
            isFirstCategory,
            isLastCategory,
            active_sub_index: 0,
            showDrop: false
        }, function () {
            that.getHotList();
        });
    },
    changeCategory: function (t) {
        var idx = t.currentTarget.dataset.index;
        console.log(idx)
        idx !== this.data.rushCategoryData.activeIndex && this.setCategory(idx);
    },
    authModal: function (t) {
        console.log(t);
        t.detail && this.setData({ needAuth: true });
        if (this.data.needAuth) {
            this.setData({
                showAuthModal: !this.data.showAuthModal
            });
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        this.setData({ tabbarRefresh: true })
        this.get_cate_list().then(() => {
            if (that.isFirst > 1) {
                that.$data.rushCategoryId = app.globalData.typeCateId || 0;
                console.log('typeCateId', that.$data.rushCategoryId);
                app.globalData.typeCateId = 0;
                if (that.$data.rushCategoryId) {
                    let rushCategoryData = that.data.rushCategoryData;
                    let tabs = rushCategoryData.tabs;
                    let active_cate_id = that.$data.rushCategoryId;
                    rushCategoryData.activeIndex = tabs.findIndex((p) => {
                        return p.id == active_cate_id
                    }) || 0;
                    that.setData({
                        rushCategoryData
                    }, () => {
                        that.setCategory(rushCategoryData.activeIndex);
                    })
                }
            }
        });
        util.check_login_new().then((res) => {
            if (res) {
                (0, status.cartNum)('', true).then((res) => {
                    res.code == 0 && that.setData({
                        cartNum: res.data
                    })
                });
                if (that.isFirst >= 1) {
                    let goodsListCarCount = app.globalData.goodsListCarCount; //[{ actId: 84, num: 2}]
                    let rushList = that.data.list;
                    if (goodsListCarCount.length > 0 && rushList.length > 0) {
                        let changeCarCount = false;
                        goodsListCarCount.forEach(function (item) {
                            let k = rushList.findIndex((n) => n.actId == item.actId);
                            if (k != -1 && rushList[k].skuList.length === 0) {
                                let newNum = item.num * 1;
                                rushList[k].car_count = newNum >= 0 ? newNum : 0;
                                changeCarCount = true;
                            }
                        })

                        that.setData({
                            list,
                            changeCarCount
                        })
                    }
                }
            } else {
                that.setData({
                    needAuth: true
                })
            }
        })
        that.isFirst++;
    },
    /**
     * 切换导航
     */
    switchNav: function (e) {
        let that = this;
        let curIdx = e.target.dataset.current * 1;
        if (this.data.currentTab === curIdx) return false;
        let groups = [
            { text: '删除', type: 'warn', value: 1 },
            { text: '编辑', value: 2 },
            { text: '修改库存', value: 5 }
            // { text: '编辑', value: 3 }
        ]
        if (curIdx == 0) {
            groups = [
                { text: '删除', type: 'warn', value: 1 },
                { text: '编辑', value: 4 },
                { text: '修改库存', value: 5 }
                // { text: '编辑', value: 3 }
            ]
        } else if (curIdx == 4) {
            groups = [
                { text: '删除', type: 'warn', value: 1 },
                { text: '修改库存', value: 5 }
                // { text: '编辑', value: 3 }
            ]
        } else if (curIdx == 8) {
            groups = [
                { text: '删除', type: 'warn', value: 1 },
                { text: '编辑', value: 2 },
                { text: '修改库存', value: 5 }
            ]
        }
        this.$data.pageNum = 1;
        this.setData({
            currentTab: 1 * e.target.dataset.current,
            groups,
            list:[]
        }, () => {
            that.getHotList();
        });
    },
    watchPassWord: function (event) {
        this.setData({
            keywords: event.detail.value
        })
        console.log(event.detail.value);
    },
    goResult: function (e) {
        var that = this;
        this.$data.pageNum = 1;
        this.setData({
            list: []
        }, () => {
            this.getHotList();
        });
        // this.getHotList();
    },
    tochangestatus:function(e){
        console.log(e);
        var grounding = e.currentTarget.dataset.grounding, id = e.currentTarget.dataset.id, index = e.currentTarget.dataset.index,changeAfter;
        if (grounding == 0){
            changeAfter = 1;
        }else{
            changeAfter = 0;
        }
        
        let that = this;
        let token = wx.getStorageSync('token');
        console.log(this.data.list);
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/index',
            data: {
                controller: 'supplymobile.change',
                token,
                id: id,
                type:'grounding',
                value: changeAfter
            },
            method: 'post',
            dataType: 'json',
            success: function (res) {
                console.log(res);
                if (res.data.code == 0) {
                    var up = "list[" + index + "].grounding";
                    that.setData({
                        [up]: changeAfter
                    })
                    app.util.message('操作成功','','success');
                } else {
                    app.util.message(res.data.msg || '提交失败', '', 'error');
                    return;
                }
                wx.hideLoading();
            }
        })
    },
    getData: function () {
        // let that = this;
        // let token = wx.getStorageSync('token');
        // let grounding = this.data.currentTab;
        // let keywords = this.keywords;

        // wx.showLoading();
        // app.util.request({
        //     url: 'entry/wxapp/index',
        //     data: {
        //         controller: 'supplymobile.get_supply_goodslist',
        //         token,
        //         grounding,
        //         page: this.page,
        //         gid:1,
        //         keywords
        //     },
        //     dataType: 'json',
        //     success: function (res) {
        //         if (res.data.code == 0) {
        //             let h = {};
        //             let list = res.data.data;
        //             if (list.length == 0) {
        //                 if (that.page == 1) {
        //                     h.noData = 1;
        //                 } else {
        //                     h.loadMore = false;
        //                     h.noMore = false;
        //                     h.loadText = "没有更多记录了~"
        //                 }
        //             }
        //             if (list.length < 10) h.noMore = true;
        //             let oldList = that.data.list;
        //             list = oldList.concat(list);
        //             that.page++;
        //             that.setData({ list, ...h })
        //         } else {
        //             app.util.message(res.data.msg, 'switchTo:/lionfish_comshop/pages/user/me', 'error');
        //         }
        //         wx.hideLoading();
        //     }
        // })
    },

    handleActionsheet: function (e) {
        let idx = (e && e.currentTarget.dataset.index) || 0;
        let id = (e && e.currentTarget.dataset.id) || 0;
        let list = this.data.list;
        let goodsItem = list[idx];
        let h = {};
        if (id) { h.goodsItem = goodsItem }
        this.setData({
            showActionsheet: !this.data.showActionsheet,
            ...h
        })
    },

    handleBtn(e) {
        let goodsItem = this.data.goodsItem;
        let goodsId = goodsItem.id;
        let hasoption = goodsItem.hasoption;
        let type = e.detail.value; // 1删除 2下架 3编辑 4上下架 5修改库存
        this.handleActionsheet();
        switch (type) {
            case 1:
                this.actionConfirm('是否删除该商品').then(() => {
                    this.delGoods(goodsId)
                });
                break;
            case 2:
                wx.navigateTo({ url: `/lionfish_comshop/moduleB/supply/goodsadd?id=${goodsId}` })
                break;
            case 3:
                console.log('3编辑')
                break;
            case 4:
                wx.navigateTo({ url: `/lionfish_comshop/moduleB/supply/goodsadd?id=${goodsId}` })
                this.actionConfirm('是否上架该商品').then(() => {
                    this.upcarriage(goodsId)
                });
                break;
            case 5:
                // 修改库存
                if (hasoption == 1) {
                    wx.navigateTo({ url: `/lionfish_comshop/moduleB/supply/editSku?id=${goodsId}` })
                } else {
                    // 显示弹窗
                    this.setData({ editSkuVisible: true, editSkuNum: goodsItem.total || 0 })
                }
                break;
            default:
                console.log('默认操作')
        }
    },

    /**
     * 下架
     * @param {*} goods_id 
     */
    undercarriage: function (goods_id) {
        let that = this;
        let token = wx.getStorageSync('token');
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/index',
            data: {
                controller: 'supplymobile.down_supply_goods',
                token,
                goods_id
            },
            dataType: 'json',
            success: function (res) {
                wx.hideLoading();
                if (res.data.code == 0) {
                    let list = that.data.list || [];
                    list = list.filter(item => item.id != goods_id);
                    let h = {};
                    if (list.length == 0) h.noData = 1;
                    h.list = list;
                    that.setData(h);
                    wx.showToast({
                        title: '下架成功',
                        icon: 'none'
                    })
                } else {
                    app.util.message(res.data.msg, '', 'error');
                }
            }
        })
    },

    /**
     * 上架
     * @param {*} goods_id 
     */
    upcarriage: function (goods_id) {
        let that = this;
        let token = wx.getStorageSync('token');
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/index',
            data: {
                controller: 'supplymobile.up_supply_goods',
                token,
                goods_id
            },
            dataType: 'json',
            success: function (res) {
                wx.hideLoading();
                if (res.data.code == 0) {
                    let list = that.data.list || [];
                    list = list.filter(item => item.id != goods_id);
                    let h = {};
                    if (list.length == 0) h.noData = 1;
                    h.list = list;
                    that.setData(h);
                    wx.showToast({
                        title: '上架成功',
                        icon: 'none'
                    })
                } else {
                    app.util.message(res.data.msg, '', 'error');
                }
            }
        })
    },

    delGoods: function (goods_id) {
        let that = this;
        let token = wx.getStorageSync('token');
        wx.showLoading();
        app.util.request({
            url: 'entry/wxapp/index',
            data: {
                controller: 'supplymobile.delete_supply_goods',
                token,
                goods_id
            },
            dataType: 'json',
            success: function (res) {
                wx.hideLoading();
                if (res.data.code == 0) {
                    let list = that.data.list || [];
                    list = list.filter(item => item.id != goods_id);
                    let h = {};
                    if (list.length == 0) h.noData = 1;
                    h.list = list;
                    that.setData(h);
                    wx.showToast({
                        title: '删除成功',
                        icon: 'none'
                    })
                } else {
                    app.util.message(res.data.msg, '', 'error');
                }
            }
        })
    },

    actionConfirm: function (content) {
        return new Promise((resolve, reject) => {
            wx.showModal({
                title: '提示',
                content,
                showCancel: true,
                success: (result) => {
                    if (result.confirm) {
                        resolve();
                    } else if (result.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        })
    },

    /**
     * 修改库存
     */
    editSku: function (e) {
        if (e.detail.index == 0) {
            this.setData({ editSkuVisible: false })
        } else {
            let editSkuNum = this.data.editSkuNum;
            if (editSkuNum === '') {
                return wx.showToast({
                    title: '请输入正确的数量',
                    icon: 'none'
                })
            }
            this.subSku();
        }
    },

    subSku: function () {
        let goodsItem = this.data.goodsItem;
        let goodsId = goodsItem.id;
        console.log(goodsId);
        let editSkuNum = this.data.editSkuNum;
        let token = wx.getStorageSync('token');
        let params = {
            token,
            goods_id: goodsId,
            is_has_option: 0,
            quantity: editSkuNum
        };
        app.util.ProReq('supplymobile.modify_supply_goods_quantity', params).then(res => {
            let list = this.data.list || [];
            list.map(item => { if (item.id == goodsId) item.total = editSkuNum; })
            this.setData({ list, editSkuVisible: false, editSkuNum: 0, goodsItem: '' })
        }).catch(err => {
            app.util.message(err.msg || '请求出错', 'switchTo:/lionfish_comshop/pages/user/me', 'error');
        })
    },

    bindSkuIpt: function (e) {
        let val = e.detail.value || 0;
        this.setData({ editSkuNum: parseInt(val) });
        return parseInt(val)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.initPageData();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    // onReachBottom: function () {
    //     if (!this.data.loadMore) return false;
    //     this.getData();
    // }
})